package embyparse.noobparser;

import java.util.ArrayList;

import emby.err.SyntaxError;
import embyparse.parsetree.ParseNode;

public class GroupingPattern extends Pattern{
	/*
	public static void main(String[] args){
		RawPattern.forceLoad();

		ParseNode open = TokenAnalyzer.analyzeToken(new Token("("));
		ParseNode var = TokenAnalyzer.analyzeToken(new Token("x"));
		ParseNode close = TokenAnalyzer.analyzeToken(new Token(")"));
		ArrayList<ParseNode> stack = new ArrayList<ParseNode>();
		stack.add(open);stack.add(var);stack.add(close);
		PAREN.match(stack, null);
		System.out.println(stack);
	}
	*/


	Pattern open;
	Pattern close;
	public GroupingPattern(int precedence, String name, Pattern open, Pattern close){
		super(name, precedence);
		//this.open = TokenAnalyzer.analyzeToken(new Token(open));
		//this.close = TokenAnalyzer.analyzeToken(new Token(close));
		this.open = open;
		this.close = close;
		PatternDefinitions.MATCHING_PATTERNS.add(this);
	}


	public ArrayList<ParseNode> match(ArrayList<ParseNode> stack, ParseNode lookahead){
		if( !stack.get(stack.size()-1).tag.equalTag(close.name)){
				return stack;
		}
		ParseNode close_group = stack.remove(stack.size()-1);
		ArrayList<ParseNode> nested = new ArrayList<ParseNode>();
		for(int i = stack.size()-1; i>=0; i--){
			//System.out.println("node: "+stack.get(i)+", tag: "+stack.get(i).tag);

			if( stack.get(i).tag.equalTag(open.name)){
				stack.remove(i);
				ParseNode p = new ParseNode(this,null,nested);
				p.setLine(close_group.lineNumber);
				//remove items from stack
				for(int j=0;j<nested.size();j++){
					stack.remove(stack.size()-1);
				}
				stack.add(p);
				m.matchFound();
				return stack;
			}
			else{
				//System.out.println("nesting: "+stack.get(i));
				nested.add(0,stack.get(i));
			}
		}

		//System.out.println("Err at line "+open_group.lineNumber);
		new SyntaxError(close_group.lineNumber,"Unclosed "+close+" at line ");
		return null;
	}

}
